package pacoteDao;

import java.sql.*;
import java.util.*;
import projetofinal.ConnectionFactory;
import projetofinal.Historico;

public class HistoricoDAO {

    private ConnectionFactory conexao = new ConnectionFactory();
    private Connection connection;
    String query;

    public HistoricoDAO() throws SQLException {
        if (connection == null || connection.isClosed()) {
            this.connection = conexao.getConnection();
        }
    }

    public boolean insert(Historico historico) throws SQLException {

        query = "insert into Historico(id,idaluno,iddisciplina,nota) values (" + historico.getId() + "," + historico.getIdaluno() + "," + historico.getIddisciplina() + "," + historico.getNota() + ")";
        Integer linha = conexao.executarNoQuery(query);

        conexao.close();
        return linha > 0;

    }

    public boolean update(Historico historico) throws SQLException {

        query = "update Historico set idaluno = " + historico.getIdaluno() + ", iddisciplina = " + historico.getIddisciplina() + ", nota = " + historico.getNota() + " where id = " + historico.getId();
        Integer linha = conexao.executarNoQuery(query);

        conexao.close();
        return linha > 0;

    }

    public boolean delete(Historico historico) throws SQLException {

        query = "delete from Historico where id = " + historico.getId();
        int linhas = conexao.executarNoQuery(query);

        conexao.close();
        return linhas > 0;

    }

    public List<Historico> consultar() throws SQLException {

        query = "select * from Historico ";
        ResultSet rset = conexao.executar(query);

        List<Historico> historicos = null;
        while (rset.next()) {
            historicos = new ArrayList<Historico>();
            Historico historico = new Historico();
            historico.setId(rset.getInt(1));
            historico.setIdaluno(rset.getInt(2));
            historico.setIddisciplina(rset.getInt(3));
            historico.setNota(rset.getInt(4));
            historicos.add(historico);
        }

        conexao.close();
        return historicos;

    }

    public Historico getById(Integer id) throws SQLException {

        query = "select * from Historico where id = " + id;
        ResultSet rs = conexao.executar(query);

        Historico historico = null;
        if (rs.next()) {
            historico = new Historico();
            historico.setId(rs.getInt(1));
            historico.setIdaluno(rs.getInt(2));
            historico.setIddisciplina(rs.getInt(3));
            historico.setNota(rs.getInt(4));
        }

        conexao.close();
        return historico;

    }
}
